package com.pet.pet05order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pet.mapper.ItemMapper;
import com.pet.mapper.OrderMapper;
import com.pet.pet05order.feign.RemoteItemService;
import com.pet.pet05order.feign.RemoteUserService;
import com.pet.pojo.Item;
import com.pet.pojo.Order;
import com.pet.pojo.OrderPre;
import com.pet.pojo.User;
import com.pet.service.ItemDescService;
import com.pet.service.MessageService;
import com.pet.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private RemoteItemService remoteItemService;

    @Transactional
    @Override
    public Boolean addOrder(String userName, Integer itemId, Integer num) {
        //根据用户名查询用户信息
        User user = remoteUserService.getUserByName(userName);
        //根据商品id查询商品信息
        Item item = remoteItemService.getItemById(itemId);
        //创建订单对象
        Order order = new Order();
        order.setUserId(user.getId())
                .setItemId(itemId)
                .setTitle(item.getTitle())
                .setPrice(item.getPrice())
                .setAddr(user.getAddr())
                .setStatus(3)
                .setNum(num);
        System.out.println(order);
        //向数据库中添加数据
        int insert = orderMapper.insert(order);
        //商品表中的库存减少
        Integer store = item.getNum();
        store = store - num;
        item.setNum(store);
        System.out.println("-----------------"+item);
        remoteItemService.storeDesc(item);
        if(insert == 0){
            return false;
        }
        return true;
    }

    @Override
    public List<Order> getAllOrder(String userName) {
        //获取用户id
        User user = remoteUserService.getUserByName(userName);
        Integer userId = user.getId();
        //获取订单信息
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId)
                .orderByDesc("created");
        List<Order> orders = orderMapper.selectList(queryWrapper);
        return orders;
    }
}

